/**
 * 场景操作的相关方法
 */
var baseURL = localStorage.getItem("baseURL");

var wsURL = localStorage.getItem("wssurl");
function readLocalConfig(){
	$.getJSON("../addressConfig.json", function (data){
	    //console.log(data);
		baseURL = data.baseAPI.baseurl;
		localStorage.setItem("baseURL",baseURL);
		//下面为webSocket地址
		wsURL = data.baseAPI.socketUrl;
	});
}
if(!baseURL && !wsURL){
  readLocalConfig();
}
var isSecond = 0;
var token = localStorage.getItem("attoken");
//判断是否为键值对对象的函数；
function isObject(obj) {
	return obj.constructor.toString().indexOf("Object") > -1;
};
!function(win){
    "use strict";
    var WebSocketClilent = function(){

    }
    WebSocketClilent.prototype={
        constructor:WebSocketClilent,
        /**
         * 初始websocket链接
         */
        initWebSocket:function(stage_id) {
            this.stage_id=stage_id;
            if (window.WebSocket) {
                try{
                webSocketClilent.websocket.close();
                webSocketClilent.websocket=null;
                }catch (e){

                }
               // var websocket = new WebSocket(encodeURI(initjson.webSocketUrl));
				var websocket = new WebSocket(encodeURI(wsURL));
                this.websocket=websocket;
                websocket.onopen = function() {
                   // $("#ljzt").html("<span style='font-size:30px;color:#00FF00'>●</span>");
                    websocket.send(stage_id+"ONLINE");//上线
					$.ajax({
					    type: "post",
					    dataType: "json",
					    url: baseURL+"api/draw/refresh",
					    data: {
					        'id': stage_id,
					        'token': localStorage.getItem("attoken")
					    },
					    success: function(data) {
					        //console.log(data);
					        if (data && data.result == 'success') {
					            console.log("组态数据刷新成功")
					                //console.log(itemData);
					        }
					        setTimeout(function() {
					            isSecond = 1;
					        }, 20000)
					    },
					    error: function(jqXHR) {
					        console.log("发生错误：" + jqXHR.status);
					    }

					});
                    // try{
                    // clearInterval(webSocketClilent.intervalId);//停止心跳
                    // webSocketClilent.intervalId=null;
                    // }catch (e){

                    // }
					webSocketClilent.sendCmdWebSocketHeart();
                    webSocketClilent.intervalId = setInterval(webSocketClilent.sendCmdWebSocketHeart, 10000);

                    try{
                        clearInterval(webSocketClilent.intervalCxlj);//停止重连
                    }catch(e){}
                }
                websocket.onerror = function(e) {
                    //连接失败
                   // $("#ljzt").html("<span style='font-size:30px;color:#FF0000'>●</span><span style='font-size:16px;color:#FF0000'>失败</span>");
                    console.log("websocket链接异常");
                    webSocketClilent.websocket.close();
                    webSocketClilent.websocket=null;
                    return;

                }
                websocket.onclose = function() {// 不要用这个事件离开 要主动调用
                    try{
                    //clearInterval(webSocketClilent.intervalId);//停止心跳
                    webSocketClilent.websocket.close();
                    webSocketClilent.websocket=null;
                    //websocket.send(cjkzbh+"LEAVE");//离开
                    }catch(e){

                    }

                }
                //消息接收
                websocket.onmessage = function(message) {
                    //console.log(new Date()+":"+message.data);
                    //debugger;
                    var serialDataJson = eval("["+message.data+"]");
                    serialDataJson = serialDataJson[0];
                    var  messagetype =  serialDataJson["MESSAGETYPE"]; ////01 业务数据 02 提醒数据
                    if(messagetype=="02"){//提醒数据




                    }if(messagetype=="03"){//网络诊断




                    }if(messagetype=="04"){//命令发送后的提醒数据
                        var  messageContent =  serialDataJson["MESSAGECONTENT"];
                        layer.msg(messageContent, {
                            offset: 't',
                            anim: 6,
                            icon:1
                        });

                    }if(messagetype=="05"){//心跳

                        //var  messageContent =  serialDataJson["MESSAGECONTENT"];
                       // $("#xtzt").html("<span style='font-size:30px;color: #00ff00'>●</span>");
                       // console.log(messageContent);

                    }if(messagetype=="01"){//业务数据
                        //因为没有数据时，后台传的是空数组[],所以加此判断
						var messageContent = serialDataJson["MESSAGECONTENT"];
                        if(isObject(messageContent)){
                        	messageContentTemp = messageContent
                            //console.log(messageContentTemp);
                           // $("#sssj").html(new Date().Format("yyyy-MM-dd hh:mm:ss")+"=>"+JSON.stringify(messageContent));

                        	stageView.setStageData(messageContent);
                        }
                    }

                }
            }else{
                layer.msg('该浏览器不支持Websocket', {
                    offset: 't',
                    anim: 6,
                    icon:2
                });
            }
        },
        /**
         * 心跳
         */
        sendCmdWebSocketHeart:function(){
            // console.log("心跳开始HEARTCMD");
            // try{
            // webSocketClilent.websocket.send(webSocketClilent.stage_id +"HEARTCMD"+"00000");//发送命令
            //     console.log("  bufferedAmount:"+webSocketClilent.websocket.bufferedAmount+"  CLOSED:"+webSocketClilent.websocket.CLOSED+"   CLOSING:"+ webSocketClilent.websocket.CLOSING+"  CONNECTING:"+ webSocketClilent.websocket.CONNECTING +"   OPEN:"+webSocketClilent.websocket.OPEN+"  readyState:"+webSocketClilent.websocket.readyState);
            // }catch (e) {

            // }
            webSocketClilent.websocket.send(localStorage.getItem("stageId") + "HEARTCMD" + localStorage.getItem("attoken") + "HEARTCMD" + isSecond); //发送命令
            if(webSocketClilent.websocket==null||webSocketClilent.websocket.readyState==3||webSocketClilent.websocket.readyState==2){
                //$("#xtzt").html("<span style='font-size:30px;color: #ff0000'>●</span><span style='font-size:16px;color: #ff0000'>停止</span>");
                clearInterval(webSocketClilent.intervalId);//停止心跳
                webSocketClilent.intervalCxlj = setInterval(webSocketClilent.reconnect, 25000);//启动重连 websocket客户端连接超时时间是 20秒 这里设置长一点，时间短了 有可能在服务器正常的瞬间 同时连接上多个相同的链接
            }
        },
        reconnect:function(){
            //$("#ljzt").html("<span style='font-size:30px;color:#FFFF00'>●</span><span style='font-size:16px;color:#FFFF00'>正在重新链接</span>");
            webSocketClilent.initWebSocket(localStorage.getItem("stageId"));

            //console.log("重连之后==  bufferedAmount:"+webSocketClilent.websocket.bufferedAmount+"  CLOSED:"+webSocketClilent.websocket.CLOSED+"   CLOSING:"+ webSocketClilent.websocket.CLOSING+"  CONNECTING:"+ webSocketClilent.websocket.CONNECTING +"   OPEN:"+webSocketClilent.websocket.OPEN+"  readyState:"+webSocketClilent.websocket.readyState);

        },

		sendCmdWebSocket: function(cmdstr) {
		    console.log(cmdstr);
		    var cmdText = cmdstr.split("CONTROLCMD")[0];
		    var cmdType = cmdstr.split("CONTROLCMD")[2];
		    //console.log(cmdType);
		    if (cmdType == "开关") {
		        var cmdOper = cmdText == 1 ? '打开' : '关闭';
		        layer.confirm('确认要' + cmdOper + '此开关吗？', {
		            btn: ['确定', '取消'] //按钮
		        }, function(index) {
		            try {
		                //debugger;
		                webSocketClilent.websocket.send(localStorage.getItem("stageId") + "CONTROLCMD" + cmdstr); //发送命令
		                layer.close(index);
		            } catch (e) {
		                layui.layer.msg('websocket链接异常，请确认网络！', {
		                    offset: 't',
		                    anim: 6,
		                    icon: 2
		                });
		            }

		        }, function() {

		        });
		    } else if (cmdType == "复位") {
		        let timeValue = Number(cmdstr.split("CONTROLCMD")[3]) * 1000;
		        let type = Number(cmdstr.split("CONTROLCMD")[4]);
		        //console.log(type);
		        layer.confirm('确认要执行此操作吗？', {
		            btn: ['确定', '取消'] //按钮
		        }, function(index) {
		            try {
		                //debugger;
		                if (type == 1) {
		                    webSocketClilent.websocket.send(localStorage.getItem("stageId") + "CONTROLCMD1" + cmdstr); //发送命令
		                    layer.close(index);
							setTimeout(function() {
		                        webSocketClilent.websocket.send(localStorage.getItem("stageId") + "CONTROLCMD0" + cmdstr); //发送命令
		                    }, timeValue)
		                } else {
		                    webSocketClilent.websocket.send(localStorage.getItem("stageId") + "CONTROLCMD0" + cmdstr); //发送命令
		                    layer.close(index);
							setTimeout(function() {
		                        webSocketClilent.websocket.send(localStorage.getItem("stageId") + "CONTROLCMD1" + cmdstr); //发送命令
		                    }, timeValue)
		                }
		            } catch (e) {
		                layui.layer.msg('websocket链接异常，请确认网络！', {
		                    offset: 't',
		                    anim: 6,
		                    icon: 2
		                });
		            }

		        }, function() {

		        });
		    } else if(cmdType == "写值"){
				var  confirmText=cmdstr.split("CONTROLCMD")[3]?cmdstr.split("CONTROLCMD")[3]:'确认要设置为【' + cmdText + '】吗？';
				layer.confirm(confirmText, {
				    btn: ['确定', '取消'] //按钮
				}, function(index) {
				    try {
				        //debugger;
				        webSocketClilent.websocket.send(localStorage.getItem("stageId") + "CONTROLCMD" + cmdstr); //发送命令
				        layer.close(index);
				    } catch (e) {
				        layui.layer.msg('websocket链接异常，请确认网络！', {
				            offset: 't',
				            anim: 6,
				            icon: 2
				        });
				    }

				}, function() {

				});
			}else {
		        layer.confirm('确认要设置为【' + cmdText + '】吗？', {
		            btn: ['确定', '取消'] //按钮
		        }, function(index) {
		            try {
		                //debugger;
		                webSocketClilent.websocket.send(localStorage.getItem("stageId") + "CONTROLCMD" + cmdstr); //发送命令
		                layer.close(index);
		            } catch (e) {
		                layui.layer.msg('websocket链接异常，请确认网络！', {
		                    offset: 't',
		                    anim: 6,
		                    icon: 2
		                });
		            }

		        }, function() {

		        });
		    }

		}
        // sendCmdWebSocket:function (cmdstr) {
        //     var cmdText =cmdstr.split("CONTROLCMD")[0];
        //     layer.confirm('确认要发送命令【'+cmdText+'】吗？', {
        //         btn: ['确定','取消'] //按钮
        //     }, function(index){
        //         try{
        //             webSocketClilent.websocket.send(webSocketClilent.stage_id +"CONTROLCMD"+cmdstr);//发送命令
        //             layer.close(index);
        //         }catch (e) {
        //             layui.layer.msg('websocket链接异常，请确认网络！', {
        //                 offset: 't',
        //                 anim: 6,
        //                 icon:2
        //             });
        //         }

        //     }, function(){

        //     });

        // },
        // sendCmdMcxhWebSocket:function (cmdstr) {//脉冲信号
        //     try{
        //         webSocketClilent.websocket.send(webSocketClilent.stage_id +"CONTROLCMD"+cmdstr);//发送命令
        //     }catch (e) {
        //         layui.layer.msg('websocket链接异常，请确认网络！', {
        //             offset: 't',
        //             anim: 6,
        //             icon:2
        //         });
        //     }

        // }


    }
    win.WebSocketClilent = WebSocketClilent;
}(window);
